<template>
	<div id="userDetail">
		<div class="title"><a class="backPage iconfont icon-icon-test" @click="$router.back(-1)"></a>用户详情</div>
		<el-upload 
			:show-file-list="false" 
			:action="baseUrl + '/api/console/user/avatar/upload'"
			:headers="{authorizedkey:authorized_key}"
			:on-success="avatarUpload"
			:data="{
				user_id: detail.user_info.id,
				bid: createBid()
			}"
			class="elupload" v-if="detail != null">
			<img :src="detail.user_info.avatar+Date.now()" class="head" />
		</el-upload>
		<el-row>
			<el-button plain class="f1" @click="resetPass()">重置密码</el-button>
			<el-button plain class="f1" @click="$router.push(`/user/template?uid=${detail.user_info.id}`)">他的模板</el-button>
			<el-button plain class="f1" @click="handleBalancePopShow">余额充值</el-button>
			<el-button plain class="f1" @click="$router.push(`/capital/detailed/page/1/user_id/${detail.user_info.id}`)">资金明细</el-button>
			<el-button plain class="f1" @click="$router.push(`/capital/integral/page/1/user_id/${detail.user_info.id}`)">积分明细</el-button>
			<el-button plain class="f1" @click="riskShow = true;">不良记录</el-button>
			<template
				v-if="detail.user_info.type == 1"
			>
				<el-button plain class="f1" @click="handlePopShow">
					排行榜数据
				</el-button>
			</template>
		</el-row>
		<div v-loading="loading" style="min-height: 300px;">
		<el-form class="form" label-position="top" v-if="detail !== null">
			<div class="title titles">基本信息</div>
			<el-row :gutter="25">
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="用户昵称">
							<el-input v-model.trim="detail.user_info.nick_name"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="成长值">
							<el-input type="number" v-model.number.trim="detail.user_balance.credit_score"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="手机号码">
							<el-input v-model.trim="detail.user_info.mobile"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="设备号">
							<el-input v-model.trim="detail.device_number"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="下级佣金%">
							<el-input v-model.trim="detail.user_setting.invite_ratio.first"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="下下级佣金%">
							<el-input v-model.trim="detail.user_setting.invite_ratio.seconde"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="积分余额">
							<el-input v-model.trim="detail.user_balance.score"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="抽奖次数">
							<el-input v-model.trim="detail.user_balance.lottery_draw_times"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="支付宝姓名">
							<el-input v-model.trim="detail.user_info.alipay_name"></el-input>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="支付宝账号">
							<el-input v-model.trim="detail.user_info.alipay_id"></el-input>
						</el-form-item>
					</div>
				</el-col>
			</el-row>

			<div class="title titles">权限管理</div>
			<el-row :gutter="25">
				<el-col :span="24">
					<div class="grid-content bg-purple">
						<el-form-item label="特殊设置">
							<el-checkbox v-model="detail.user_setting.is_open_profile">主页公开</el-checkbox>
							<el-checkbox v-model="detail.user_setting.is_allow_order">允许抓单</el-checkbox>
							<el-checkbox v-model="detail.user_setting.is_auto_pass">发任务秒审</el-checkbox>
							<el-checkbox v-model="detail.user_setting.is_allow_invite_ratio">特殊抽佣</el-checkbox>
							<el-checkbox v-model="detail.user_info.type">
								系统用户
							</el-checkbox>
							<!-- <el-checkbox :true-label="1" :false-label="0" label="是否员工"></el-checkbox> -->
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="24">
					<div class="grid-content bg-purple">
						<el-form-item label="账号状态">
							<el-checkbox v-model="detail.user_info.status.Login">禁止登录</el-checkbox>
							<el-checkbox v-model="detail.user_info.status.Withdraw">禁止提现</el-checkbox>
							<el-checkbox v-model="detail.user_info.status.AcceptTask">禁止接任务</el-checkbox>
							<el-checkbox v-model="detail.user_info.status.PublishTask">禁止发任务</el-checkbox>
							<el-checkbox v-model="detail.user_info.status.Exchange">禁止兑换</el-checkbox>
							<el-input v-model.trim="detail.user_info.status_text" placeholder="请输入封禁原因" style="width:260px;margin-left:25px;"></el-input>
						</el-form-item>
					</div>
				</el-col>
			</el-row>

			<div class="title titles">其它信息</div>
			<el-row :gutter="25" class="other">
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="最后登录IP">
							{{detail.user_info.last_ip}}
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="所属地区">
							{{detail.user_info.last_area}}
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="最后使用时间">
							{{detail.user_info.last_time | dateFormat('yyyy-MM-dd hh:mm:ss')}}
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="注册时间">
							{{detail.user_info.last_time | dateFormat('yyyy-MM-dd hh:mm:ss')}}
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="累计发布任务">
							<router-link class="blue" :to="`/task/?searchType=user_id&searchText=${detail.user_info.id}`">{{detail.task_count}}次</router-link>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="累计接受任务">
							<router-link class="blue" :to="`/task/accept/?searchText=${detail.user_info.id}&searchType=user_id`">{{detail.task_accept_count}}次</router-link>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="Ta去举报">
							<router-link class="blue" :to="`/task/arbitration/?searchText=${detail.user_info.id}&searchType=publish_user_id`">{{detail.user_arbitration_publish}}次</router-link>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="Ta被举报">
							<router-link class="blue" :to="`/task/arbitration/?searchText=${detail.user_info.id}&searchType=accept_user_id`">{{detail.user_arbitration_accept}}次</router-link>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="账户余额">
							<font class="red">{{detail.user_balance.balance | transPrice}}元</font>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="冻结资金">
							<font class="red">
								{{
									detail.user_Frozen_balance | transPrice
								}}元</font>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="累计充值">
							<font class="red">{{detail.user_recharge | transPrice}}元</font>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="累计提现">
							<font class="red">{{detail.user_cash | transPrice}}元</font>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="邀请累计人数">
							<router-link class="blue" :to="`/user/subordinate/${detail.user_info.id}`">下级{{detail.inviter_1_count}}人  下下级{{detail.inviter_2_count}}人</router-link>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="所属上级">
							<router-link v-if="detail.inviter" class="blue" :to="`/user/detail/${detail.inviter_id}`">{{detail.inviter}}</router-link>
							<span v-else>官方注册</span>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="性别">
							{{['未知','男','女'][detail.user_info.gender]}}
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="权限">
							<div class="tableBtn">
								<a @click="loginSimulation" class="blue">模拟登录</a>
								<a @click="logoutUser" class="blue">踢他下线</a>
							</div>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="QQ绑定">
							<div class="userHead" v-if="socialQQ">
								<img :src="socialQQ.avatar" class="square" />
								{{socialQQ.nickname}}
							</div>
							<span v-else>未绑定</span>
						</el-form-item>
					</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">
						<el-form-item label="微信绑定">
							<div class="userHead" v-if="socialWX">
								<img :src="socialWX.avatar" class="square" />
								{{socialWX.nickname}}
							</div>
							<span v-else>未绑定</span>
						</el-form-item>
					</div>
				</el-col>
			</el-row>
			<el-button type="primary" @click="updateUserInfo" style="margin-top:15px;">立即保存</el-button>
		</el-form>
		</div>
		<el-dialog title="提示" :visible.sync="handleShow" width="500px">
            <el-form label-position="top" class="form">
                <el-row :gutter="25">
                    <el-col :span="24">
                        <div class="grid-content bg-purple">
                            <el-form-item label="昵称">
                                <el-input
                                    v-model="virtualUser.user_name"
                                    disabled=""
                                ></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="grid-content bg-purple">
                            <el-form-item label="添加邀请数量">
                                <el-input
                                    v-model="virtualUser.inviter_count"
                                    type="number"
                                ></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="grid-content bg-purple">
                            <el-form-item label="添加收益">
                                <el-input
                                    v-model="virtualUser.income"
                                    type="number"
                                ></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handlePopShow">取 消</el-button>
                <el-button type="primary" 
                    :loading="popBtnLoad"
                    @click="addUserRankWill"
                >确 定</el-button>
            </span>
        </el-dialog>
		<el-dialog title="用户近100条触发平台风控记录" :visible.sync="riskShow" width="600px">
			<div class="riskShow" v-if="detail != null">
				<p v-if="detail.user_abnormal.length == 0">无风控记录</p>
				<p v-else :key="index" v-for="(item,index) in detail.user_abnormal"><span style="display:inline-block;width:150px;">{{item.time_created | dateFormat}}:</span> {{item.remark}}</p>
			</div>
		</el-dialog>
		<el-dialog
			title="提示"
			:visible.sync="balancePop"
			width="30%"
			center
		>
			<div>
				需要充值多少余额，可为负数
			</div>
			<div class="flex priceWarp">
				<div class="mr10">
					金额:
				</div>
				<div class="flex1">
					<input type="number" placeholder="请输入充值金额"
						class="_input"
						v-model="balancePar.price"
					/>
				</div>
			</div>
			<div class="flex priceWarp">
				<div class="mr10">
					原因:
				</div>
				<div class="flex1">
					<input type="text" placeholder="请输入充值原因"
						class="_input"
						v-model="balancePar.remarks"
					/>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleBalancePopShow">取 消</el-button>
				<el-button type="primary" @click="recharge">确 定</el-button>
			</span>
		</el-dialog>
	</div>	
</template>

<script>
import utils from '@/utils/index';
import env from '@/config/env';
import fetch from '@/api/axios';
import {sysToYuan, yuanToSys} from '@/utils/transPrice';
import {tsToDateFormat} from '@/utils/tsToDateFormat';
import deepClone from '@/utils/deepClone.js';
// 请求通用方法
import apiMixin from '@/mixin/apiMixin';
export default {
	mixins: [apiMixin],
	data() {
		return {
			authorized_key:  utils.handleLocalStorage.get('authorized_key'),
			baseUrl: env.baseUrl,
			bid: '',
			id: 0,
			loading: false,
			detail: {
				user_info: {
					status: {}
				},
				user_balance: {},
				user_setting: {
					invite_ratio: {}
				}
			},
			riskShow:false,
			virtualUser: {
                // 用户名字
                user_name :'',
                // 邀请数量
                inviter_count :'',
                // 本月收入
				income:'',
				userId: ''
			},
			handleShow: false,
			popBtnLoad: false,
			// 余额充值弹窗
			balancePop: false,
			balancePar: {
				price: '',
				remarks: ''
			}
		}
	},
	filters: {
		transPrice(p){
			return sysToYuan(p, 2);
		},
		dateFormat(t, format='yyyy-MM-dd hh:mm:ss'){
			return tsToDateFormat(t, format);
		},
	},
	computed: {
		socialWX(vm){
			return vm.detail.user_three.find((v)=>{
				return v.type == 1;
			});
		},
		socialQQ(vm){
			return vm.detail.user_three.find((v)=>{
				return v.type == 2;
			});
		},
		
	},
	created(){
		console.log('测试');
		this.id = this.$route.params.id;
	},
	methods: {
		// 模拟登录,获取用户token
		loginSimulation(){
			fetch.get('/api/console/user/key', {
				user_id: parseInt(this.id)
			}).then(res=>{
				let data = res.data;
				let tk = '';
				if(data.code == 0){
					tk = data.data;
					window.open(env.domainUrl+'/mine?systemtk='+tk);
				}else{
					this.$message.success(data.message);
				}
			}).catch(err=>{
				this.$message.error('网络连接失败，请稍后重试');
			});
		},
		logoutUser(){
			this.$confirm('该操作会使用户强制下线,确认执行？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				fetch.post('/api/console/admin/login/user', {
					user_id: this.id
				}).then(res=>{
					let data = res.data;
					if(data.code == 0){
						this.$message.success('操作成功');
					}else{
						this.$message.error(data.message);
					}
				}).catch(err=>{
					this.$message.error('网络连接失败，请稍后重试');
				});
			}).catch(() => {
				// nothing
			});
		},
		createBid() {
            let prefix = utils.createUploadPrefix('Avatar');
            let bid = prefix + '-' +  utils.createBidFn();
            this.bid = bid;
            return  bid;
        },
		avatarUpload(){
			this.getUserDetail();
		},
		getUserDetail(){
			let _this = this;
			this.loading = true;
			fetch.get('/api/console/user/detail', {
				user_id: this.id
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					let userDetail = data.data;
					userDetail.user_info.type = userDetail.user_info.type == 1 ? true : false;
					_this.virtualUser.userId = userDetail.user_info.id;
					_this.virtualUser.user_name = userDetail.user_info.nick_name;
					_this.detail = _this.adapteUserInfoStatus(userDetail);
				}else{
					_this.$message.error(data.data.info || data.message);
				}
			}).catch(err=>{
				_this.$message.error('网络异常，请稍后重试');
			}).finally(()=>{
				_this.loading = false;
			});
		},
		adapteUserInfoStatus(detail){
			let status = {...detail.user_info.status};
			for(let k in status){
				status[k] = !status[k];
			}
			detail.user_info.status = status;
			return detail;
		},
		updateUserInfo(){
			let _this = this;
			if(this.loading){
				return false;
			}
			this.loading = true;
			let detail = JSON.parse(JSON.stringify(this.detail));
			detail.user_info.type = detail.user_info.type ? 1 : 0;
			detail = this.adapteUserInfoStatus(deepClone(detail));
			fetch.post('/api/console/user/detail', {
				...detail
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					_this.$message.success('修改成功');
					// _this.detail = _this.adapteUserInfoStatus({...this.detail});
					_this.getUserDetail();
				}else{
					_this.$message.error(data.message);
				}
			}).catch(err=>{
				_this.$message.error('网络链接失败，请稍后重试');
			}).finally(()=>{
				_this.loading = false;
			});
		},
		resetPass(){
			let _this = this;
			this.$confirm('重置密码以后可能会导致用户无法登录，确定?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				return fetch.post('/api/console/user/repasswd',{
					user_id: _this.detail.user_info.id,
					mobile: _this.detail.user_info.mobile
				});
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					_this.$alert(`密码已成功重置，新密码为：<strong>${data.data.passwd}</strong>`, '提示', {
						dangerouslyUseHTMLString: true
					}).catch(err=>{
						// console.log(err);
					});
				}else{
					_this.$message.error(data.message);
				}
			}).catch(err=>{
				if(err != 'cancel'){
					_this.$message.error('密码重置失败');
				}
			});
		},
		handleBalancePopShow() {
			this.balancePop = !this.balancePop;
		},
		initBalancePar() {
			this.balancePar = {
				price: '',
				remarks: ''
			};
		},
		recharge(){
			let balancePar = this.balancePar;
			if(!balancePar.price) {
				this.$message.error('金额未填写');
				return;
			}
			if(!balancePar.remarks) {
				this.$message.error('原因未填写');
				return;
			}
			this.handleBalancePopShow();
			let _this = this;
			fetch.post('/api/console/user/rechargebyadmin', {
				tel: _this.detail.user_info.mobile,
				money: yuanToSys(balancePar.price),
				comment: balancePar.remarks
			}).then(res=>{
				let data = res.data;
				if(data.code == 0){
					_this.$message.success('充值成功');
					_this.initBalancePar();
					_this.getUserDetail();
				}else{
					_this.$message.error(data.data.info);
				}
			}).catch(err=>{
				_this.$message.error('网络连接失败，请稍后重试');
			});
		},
		handlePopShow() {
            this.handleShow = !this.handleShow;
		},
		addUserRankWill() {
			this.editVirtualUserDetailApi();
		},
		editVirtualUserDetailApi() {
            let virtualUser = this.virtualUser;
            let resPar = {
                user_id: virtualUser.userId,
                invite_add_count: Math.abs(virtualUser.inviter_count) || 0,
                add_money: Math.abs(virtualUser.income * 10000) || 0
            };
            resPar.load = "popBtnLoad";
            let _self = this;
            this.comResquest(this.request.editVirtualUserDetail,(res)=>{
                _self.$message.success('添加成功！');
				_self.handlePopShow();
				_self.virtualUser.invite_add_count = '';
				_self.virtualUser.income = '';
            },resPar);
        },
	},
	mounted() {
		this.getUserDetail();

	},
	watch: {
		'$route':function(to, from){
			let params = to.params;
			this.id = params.id;
			this.detail = null;
			this.getUserDetail();
		}
	}
}
</script>
<style lang="scss" scoped>
#userDetail{
	position:relative;
	.title .username{
		font-weight: normal;
	}
	.riskShow{
		margin-top: -11px;
		background: #000;
		color: #FFF;
		border-radius: 4px;
		padding: 20px 22px;
		font-size: 14px;
		line-height: 29px;
		max-height: 400px;
		overflow-y:auto;
	}
	.form{
		margin-top:45px;
	}
	.titles{
		margin-top:25px;
		margin-bottom:12px;
		font-size:19px;
	}
	.elupload{
		position:absolute;
		right:0;
		top:0;
		.head{
			display:block;
			width:70px;
			height:70px;
			border-radius:50%;
			margin-top:5.5px;
		}
	}
	.square{
		width:25px;
		height:25px;
		vertical-align: middle;
	}
	.userHead{
		cursor: text;
	}
	.other .el-form-item__content {
		line-height: 40px;
		position: relative;
		font-size: 14px;
		color: #767676;
	}
}
.priceWarp{
	padding: 10px 0;
	line-height: 40px;
	._input{
		-webkit-appearance: none;
		background-color: #FFF;
		background-image: none;
		border-radius: 4px;
		border: 1px solid #DCDFE6;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		color: #606266;
		font-size: inherit;
		height: 40px;
		line-height: 40px;
		outline: 0;
		padding: 0 15px;
		-webkit-transition: border-color .2s cubic-bezier(.645,.045,.355,1);
		transition: border-color .2s cubic-bezier(.645,.045,.355,1);
		width: 100%;
	}
}
.mr10{
	margin-right: 10px;
}
.flex{
	display: flex;
}
.flex1{
	flex: 1;
}
</style>